import { useSelector, useDispatch } from "react-redux";
import { Button, Card, Dropdown, Modal } from "antd";
import { useNavigate } from "react-router-dom";
import { setDark } from "@/store/theme";
import { ExportOutlined, CaretDownOutlined, SunOutlined, MoonOutlined } from "@ant-design/icons";
import { globalConfig } from "@/globalConfig";

import "./index.css";

const loginInfo = JSON.parse(localStorage.getItem(globalConfig.SESSION_LOGIN_INFO));

function Header() {
    const dispatch = useDispatch();
    // 主题配置
    const theme = useSelector((state) => state.theme);
    const navigate = useNavigate();
    // Antd的Modal组件API
    const [modal, contextHolder] = Modal.useModal();
    const logout = () => {
        modal.confirm({
            title: "确定要退出登录吗？",
            okText: "退出",
            icon: <ExportOutlined />,
            onOk: () => {
                window.localStorage.removeItem(globalConfig.SESSION_LOGIN_INFO);
                navigate("/login");
            },
        });
    };
    const menuItems = [
        {
            key: "exit",
            label: "退出登录",
            onClick: logout,
        },
    ];

    return (
        <Card className="M-header">
            <div className="header-wrapper">
                <div className="logo-con">
                    <img src="/vite.svg" alt="" />
                    <span className="logo-text">Vite Reate APP</span>
                </div>
                <div className="header-con">
                    {theme.dark ? (
                        <Button
                            icon={<SunOutlined />}
                            shape="circle"
                            onClick={() => {
                                dispatch(setDark(false));
                            }}
                        />
                    ) : (
                        <Button
                            icon={<MoonOutlined />}
                            shape="circle"
                            onClick={() => {
                                dispatch(setDark(true));
                            }}
                        />
                    )}
                    <Dropdown menu={{ items: menuItems }}>
                        <div>
                            <span>{loginInfo ? loginInfo.nickname : "未登录"}</span>
                            <CaretDownOutlined />
                        </div>
                    </Dropdown>
                </div>
            </div>

            {contextHolder}
        </Card>
    );
}

export default Header;
